package org.dragonnova.meetingapp.app.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.iflytek.XFRecognizer;
import com.iflytek.XFSynthesizer;
import com.ztspeech.AppAudio;
import com.ztspeech.ZTTranslate;
import com.ztspeech.vad.VadCheck;

import org.dragonnova.meetingapp.model.bean.VoiceInfo;
import org.dragonnova.meetingapp.utils.Constants;
import org.dragonnova.meetingapp.utils.LogUtil;

public class TranslationService extends Service {

    private final String TAG = TranslationService.class.getName();
    public static final String EXTRA_VAD_STOP = "onVadStop";
    public static final String EXTRA_TEMP_RESULT_CHANGED = "onTempResultChanged";
    public static final String EXTRA_RECOGNIZE_FINISHED = "onRecognizefinished";
    public static final String EXTRA_RECOGNIZED_RESULT = "onRecognized";
    public static final String EXTRA_TRANSLATED = "onTranslated";
    public static final String EXTRA_NO_RESULT = "onNoResult";

    private MyBinder mBinder = new MyBinder();
    private AppAudio mAppAudio;//录音和播放,包括录音开始、录音停止、播音开始、播音结束等
    private XFRecognizer xfRecognizer;//识别类
    private XFSynthesizer xfSynthesizer;//识别类
    private ZTTranslate ztTranslate;//翻译类
    private boolean isCH2EN;
    private String mVoicePath;//语音存放的路径

    private static final int HEADSET = 2;//标识符
    private String TempResult = "";//产生的临时的翻译结果

    public class MyBinder extends Binder {
        //提供Service对象
        public TranslationService getService() {
            return TranslationService.this;
        }

        public void startRecord(boolean isch2cn) {
            isCH2EN = isch2cn;
            TranslationService.this.startRecord(isch2cn);
        }

        public void startContinuousRecord(boolean isch2cn) {
            isCH2EN = isch2cn;
            TranslationService.this.startContinuousRecord(isch2cn);
        }

        public void stopRecord() {
            TranslationService.this.stopRecord();
        }

        public void stopContinuousRecord() {
            TranslationService.this.stopContinuousRecord();
        }

        public void cancelRecord() {
            TranslationService.this.cancelRecord();
        }

        public void stopAll() {
            TranslationService.this.stopAll();
        }

        public void playRecord(String path) {
            mAppAudio.playRecord(path);
        }

        public void playRecord(byte[] bytes) {
            mAppAudio.playRecord(bytes);
        }

        public void synthesizeContent(String content, boolean isCH2EN) {
            xfSynthesizer.start(content, isCH2EN);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler serviceHandler = new Handler() {
        Intent intent = new Intent();

        public void handleMessage(Message msg) {
            switch (msg.what) {
                //录音播音状态，检测说话状态，并每次上传1280byte至云端
                case AppAudio.RECORDING:

                    break;
                //录音结束
                case AppAudio.RECORDED:
                    break;
                //录音超过60s则停止
                case AppAudio.STOP_RECORD:
                    if (msg.arg1 == -1)
                        Toast.makeText(TranslationService.this, "录音时间请小于60s", Toast.LENGTH_SHORT).show();
                    break;
                //录音错误
                case AppAudio.RECORD_ERROR:
                    Toast.makeText(TranslationService.this, "录音产生错误", Toast.LENGTH_SHORT).show();
                    break;
                //播放语音状态
                case AppAudio.PLAYING:
                    Toast.makeText(TranslationService.this, "播放中请稍后", Toast.LENGTH_SHORT).show();
                    break;
                //播放结束
                case AppAudio.PLAYED:
                    break;
                case AppAudio.PLAY_ERROR:
                    Toast.makeText(TranslationService.this, "播放错误", Toast.LENGTH_SHORT).show();
                    break;
                //停止说话标志，结束录音
                case VadCheck.VAD_STOP:
                    intent = new Intent();
                    intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_VAD_STOP);
                    sendBroadcast(intent);
                    stopRecord();
                    break;
                //无说话标志
                case VadCheck.VAD_NOVOICE:
                    break;
                //语音识别结束
                case AppAudio.RECOGNIZED:
                    LogUtil.e(TAG, "finalResult=" + TempResult);
                    mVoicePath = msg.getData().getString("newFileName");
                    LogUtil.e(TAG, "mVoicePath =" + mVoicePath);
                    VoiceInfo recognizedData = new VoiceInfo(System.currentTimeMillis(), isCH2EN ? 'c' : 'e', TempResult);
                    intent = new Intent();
                    intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_RECOGNIZED_RESULT);
                    intent.putExtra("voiceInfo", recognizedData);
                    sendBroadcast(intent);
                    //ztTranslate.startTranslate(TempResult);
                    if (msg.arg1 == XFRecognizer.continuousMsg) {
                        TranslationService.this.startRecord(isCH2EN);
                    }
                    break;
                case AppAudio.RECOGNIZED_FINISH:
                    LogUtil.e(TAG, "Recognize finished");
                    intent = new Intent();
                    intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_RECOGNIZE_FINISHED);
                    sendBroadcast(intent);
                    break;
                //语音识别错误
                case AppAudio.RECOGNIZE_ERROR:
                    Toast.makeText(TranslationService.this, "识别错误", Toast.LENGTH_SHORT).show();
                    if (msg.arg1 == 1563645) {
                        TranslationService.this.startRecord(isCH2EN);
                    }
                    break;
                //语音识别；临时结果
                case AppAudio.RECOGNIZE_TEMP_RESULT:
                    TempResult = msg.getData().getString("tempResult");
                    intent = new Intent();
                    intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_TEMP_RESULT_CHANGED);
                    intent.putExtra("tempResult", TempResult);
                    sendBroadcast(intent);
                    LogUtil.e(TAG, "tempResult=" + TempResult);
                    break;
                //翻译结束
                case AppAudio.TRANSLATED:
                    Bundle data = msg.getData();
                    String resource = data.getString("orgTxt");
                    String translated = data.getString("tranTxt");
                    boolean isch2en = data.getBoolean("isCH2EN");
                    //判断是否有返回值或者返回值不正确
                    if (resource == null || translated == null || TextUtils.isEmpty(resource.trim()) || TextUtils.isEmpty(translated.trim()) || TextUtils.equals(resource.trim(), "服务端无返回值")) {
                        if (!mAppAudio.isRecording()) {
                            intent = new Intent();
                            intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                            intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_NO_RESULT);
                            sendBroadcast(intent);
                        }
                    } else {
                        LogUtil.e(TAG, "translated=" + translated);
                        xfSynthesizer.start(translated, isch2en);//开始合成
                        //创建javabean
                        long inserttime = System.currentTimeMillis();
                        char type = isch2en ? 'c' : 'e';
                        String orgPath = mVoicePath;
                        int orgCosttime = 10000;
                        VoiceInfo voiceInfo = new VoiceInfo(resource, translated, inserttime, type, orgPath, orgCosttime);
                        intent = new Intent();
                        intent.setAction(Constants.TRANS_BORADCAST_ACTION);
                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, EXTRA_TRANSLATED);
                        intent.putExtra("voiceInfo", voiceInfo);
                        sendBroadcast(intent);
                    }
                    break;
                case AppAudio.TRANSLATE_ERROR:
                    Toast.makeText(TranslationService.this, "翻译错误", Toast.LENGTH_SHORT).show();
                    break;
                //语音合成结束
                case AppAudio.SYNTHESIZED:

                    break;
                case AppAudio.SYNTHESIZE_ERROR:
                    Toast.makeText(TranslationService.this, "合成错误", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.e(TAG, "onCreate");
        init();
    }

    private void init() {
        //初始化录音
        mAppAudio = new AppAudio(serviceHandler);
        //初始化语音合成
        xfSynthesizer = new XFSynthesizer(serviceHandler, TranslationService.this);
        //初始化语音识别
        xfRecognizer = new XFRecognizer(serviceHandler, TranslationService.this);
        //初始化翻译
        ztTranslate = new ZTTranslate(serviceHandler);
        //初始化语音设置
        refreshTranslationSettings(true);
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.e(TAG, "onBind");
        return mBinder;
    }

    /**
     * 只有在startService的时候才会被调用
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtil.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.e(TAG, "onDestroy");
        stopAll();
        //销毁AudioRecord，AudioTrack
        mAppAudio.destroyAudioRecord();
        mAppAudio.destroyAudioTrack();
    }

    /**
     * 录音时的设置
     */
    private void refreshTranslationSettings(boolean isCH2EN) {
        if (isCH2EN) {
            ztTranslate.setLanguage(ZTTranslate.LANGUAGE_MANDARIN);
        } else {
            ztTranslate.setLanguage(ZTTranslate.LANGUAGE_ENGLISH);
        }
    }

    /**
     * 开始录音
     */
    private void startRecord(boolean isCH2EN) {
        refreshTranslationSettings(isCH2EN);
        TempResult = "";
        xfRecognizer.start(isCH2EN);
    }

    /**
     * 开始录音
     */
    private void startContinuousRecord(boolean isCH2EN) {
        refreshTranslationSettings(isCH2EN);
        TempResult = "";
        xfRecognizer.setContinuous(true);
        xfRecognizer.start(isCH2EN);
    }

    /**
     * 结束录音
     */
    private void stopRecord() {
        xfRecognizer.stop();
    }

    /**
     * 结束连续录音
     */
    private void stopContinuousRecord() {
        xfRecognizer.setContinuous(false);
        xfRecognizer.stop();
    }

    /**
     * 结束录音,且不保存，不识别
     */
    private void cancelRecord() {
        xfRecognizer.cancel();
    }

    /**
     * 停止录音,播放,停止合成及消息队列，用于重新开始录音或者退出
     */
    private void stopAll() {
        mAppAudio.stopTrack();
        xfRecognizer.cancel();
        xfSynthesizer.stopSynthesize();
        serviceHandler.removeCallbacksAndMessages(null);
    }
}
